#include "formsetdatabase.h"
#include "ui_formsetdatabase.h"
#include <jcode.h>
#include <QJsonObject>
#include <QJsonDocument>
#include <QDir>



FormSetDataBase::FormSetDataBase(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormSetDataBase)
{
    ui->setupUi(this);
    this->show();
    this->setWindowTitle("配置数据库");
    ui->txtDataBasePassWord->setEchoMode(QLineEdit::Password); //设置密码输入框
    Start();


}
void FormSetDataBase::Start(){
    QString curPath= QCoreApplication::applicationDirPath();//获取系统当前目录
    QString iniFile=QString("%1/conDataBase.ini").arg(curPath);
    QString str=JCode::OpenText(iniFile);
    str=str.replace("\n","");
    str=JCode::toXOR(str,'J'); //解密
    //QMessageBox::warning(this,"警告",str);
    if (str.left(1)=="{"){
        QJsonObject obj;
        obj=JCode::QStringTOQJson(str); //转JSON
        ui->txtDataServer->setText(obj["DataBaseServer"].toString());
        ui->txtDataBaseName->setText(obj["DataBaseName"].toString());
        ui->txtDataBaseUSerName->setText(obj["DataBaseUserName"].toString());
        ui->txtDataBasePassWord->setText(obj["DataBasePassWord"].toString());
        ui->txtDataBasePort->setText(obj["DataBasePort"].toString());
        ui->txtUpFileURL->setText(obj["UpFileURL"].toString());
    }



    ui->cmbDataBaseTYPE->clear();
    ui->cmbDataBaseTYPE->addItem("mySQL");


}

FormSetDataBase::~FormSetDataBase()
{
    delete ui;
}

void FormSetDataBase::on_cmdCancel_clicked()
{
    this->close();
}

void FormSetDataBase::on_cmdOK_clicked()
{

    QJsonObject obj;
    obj.insert("DataBaseTYPE", ui->cmbDataBaseTYPE->currentText());
    obj.insert("DataBaseServer", ui->txtDataServer->text());
    obj.insert("DataBasePort", ui->txtDataBasePort->text());
    obj.insert("DataBaseName", ui->txtDataBaseName->text());
    obj.insert("DataBaseUserName", ui->txtDataBaseUSerName->text());
    obj.insert("DataBasePassWord", ui->txtDataBasePassWord->text());
    obj.insert("UpFileURL", ui->txtUpFileURL->text());
    //qDebug() << obj;
    QString INI="";
    INI=JCode::QJsonTOQString(obj); //转QString
    INI=JCode::toXOR(INI,'J'); //加密

    QString curPath=QCoreApplication::applicationDirPath();//获取系统当前目录;//获取系统当前目录
    QString iniFile=QString("%1/conDataBase.ini").arg(curPath);
    if (JCode::SaveText(iniFile,INI)==false){
        QMessageBox::warning(this,"警告","文件保存失败！");
    }else{
        QMessageBox::information(this,"提示信息","文件保存成功！");
        this->close();
        emit sendData("ok");

    }
}


void FormSetDataBase::on_cmdPing_clicked()
{

    bool m_state=false;
    QProcess cmd;	//类似于window里面的cmd命令
    QTextCodec *codec = QTextCodec::codecForName("GBK");
    QString outstr;
    while(1)
    {
        cmd.start("ping "+ui->txtDataServer->text() + " -n 1");	//ping ip地址 -n 1表示只ping一次就结束
        cmd.waitForFinished(-1);			//等待ping完成
        outstr = codec->toUnicode(cmd.readAll());	//将ping之后的结果全部读到outstr中
        if(-1!=outstr.indexOf("往返行程的估计时间"))	//通过判断有无“往返行程的估计时间”这几个字来检测网路是否通
        {
            if(!m_state)	//通过m_state变量使网络无论在通或不通只发送一次信号
            {
                //qDebug() << "网络连接成功";
                QMessageBox::information(this,"提示信息","服务器连接成功！");
                //emit signal_networkstate(true);	//发送网络连接的信号
                m_state = true;
                return;
            }
        }
        else
        {
            if(m_state)
            {
                //qDebug() << "网络断开,尝试重新连接";
                QMessageBox::information(this,"提示信息","服务器连接失败！");
                //emit signal_networkstate(false);	//发送网络断开的信号
                m_state = false;
                return;
            }
        }
        //msleep(100);
    }

}

void FormSetDataBase::on_cmdtTest_clicked()
{
    //数据库驱动类型为mySQL 运行前先测试一下数据库是否正常连接
    mySQL::cn.setHostName(ui->txtDataServer->text());
    mySQL::cn.setPort(ui->txtDataBasePort->text().toInt());                 //连接数据库端口号，与设置一致
    mySQL::cn.setDatabaseName(ui->txtDataBaseName->text());      //连接数据库名，与设置一致
    mySQL::cn.setUserName(ui->txtDataBaseUSerName->text());          //数据库用户名，与设置一致
    mySQL::cn.setPassword(ui->txtDataBasePassWord->text());    //数据库密码，与设置一致
    mySQL::cn.open();
    if(!mySQL::cn.open())                                      //打开数据库
    {
        qDebug()<<mySQL::cn.lastError().text();
        QMessageBox::critical(0, QObject::tr("测试数据库失败！！"), mySQL::cn.lastError().text());
                                           //打开失败
    }
    else
    {
        //qDebug()<<"打开数据库成功!";
        QMessageBox::information(this,"提示信息","测试数据库成功！！");
    }
}

void FormSetDataBase::on_cmdtCreatTable_clicked()
{
    //数据库驱动类型为mySQL 运行前先测试一下数据库是否正常连接
    mySQL::cn.setHostName(ui->txtDataServer->text());
    mySQL::cn.setPort(ui->txtDataBasePort->text().toInt());                 //连接数据库端口号，与设置一致
    mySQL::cn.setDatabaseName(ui->txtDataBaseName->text());      //连接数据库名，与设置一致
    mySQL::cn.setUserName(ui->txtDataBaseUSerName->text());          //数据库用户名，与设置一致
    mySQL::cn.setPassword(ui->txtDataBasePassWord->text());    //数据库密码，与设置一致
    mySQL::cn.open();
    if(!mySQL::cn.open())                                      //打开数据库
    {
        qDebug()<<mySQL::cn.lastError().text();
        QMessageBox::critical(0, QObject::tr("测试数据库失败！！"), mySQL::cn.lastError().text());
                                           //打开失败
    }
    else
    {
        //qDebug()<<"打开数据库成功!";
        //QMessageBox::information(this,"提示信息","测试数据库成功！！准备初始化");
        QString str=QString("测试数据库成功！！可以初始化\n");
        str+="初始化前请确保这是一个全新的数据库，里面没有任何表！！！\n";
        str+="是否继续【y/n】\n";
        if (QMessageBox::information(NULL, "提醒", str,QMessageBox::Yes | QMessageBox::No, QMessageBox::No)==QMessageBox::Yes){
            QString Url="http://jinesc.cn/zb_users/upload/2021/12/fos.txt";  //建表SQL 语句的下载地址
            QString curPath= QCoreApplication::applicationDirPath();//获取系统当前目录
            QString downloadFile=QString("%1/FOSDataBase.SQL").arg(curPath);
            QString SQLinfo="";
            if (JCode::DownloadURL(downloadFile,Url)==true){
                //下载成功
                QString FOSDataBase=JCode::OpenText(downloadFile);
                //qDebug() << FOSDataBase + "\n";
                QStringList sl=FOSDataBase.split("\n");
                QString SQL="";
                for (int i=0; i<sl.count(); i++){
                    QString  tmp=sl.at(i);
                    //qDebug() << tmp.left(2) + "\n";
                    if (tmp.left(2)=="--"){
                        if (SQL!=""){

                            QSqlQuery query(mySQL::cn);
                            //qDebug() << SQL+"\n";
                            query.exec(SQL);

                            if (query.lastError().text().trimmed()!=""){
                                SQLinfo+=query.lastError().text()+"\n";
                            }
                            /*
                             if (query.lastQuery().trimmed()!=""){
                                SQLinfo+=query.lastQuery().trimmed()+"\n";
                            }
                            */
                            SQL="";
                        }
                    }else{
                        SQL+=tmp;
                    }
                }
                if(SQLinfo!=""){
                    QMessageBox::information(this,"错误信息！",SQLinfo);
                }else{
                    QMessageBox::information(this,"提示信息","初始化成功");
                }


            }

        }


    }

}
